package site.kitcheng.springboottest.infra.manager;

import lombok.extern.slf4j.Slf4j;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: AsyncManager
 * Package: site.kitcheng.springboottest.infra.manager
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/3/21 14:45
 * @Version 1.0
 */
@Slf4j
public class AsyncManager {

    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;


    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor =initExecutor();

    private ScheduledExecutorService initExecutor() {
        try {
            ScheduledExecutorService service = SpringUtils.getBean("scheduledExecutorService");
            if (service != null){
                return service;
            }
            return  new ScheduledThreadPoolExecutor(5);

        } catch (Exception e) {
            return new ScheduledThreadPoolExecutor(5);
        }
    }

    private AsyncManager(){
    }

    private static AsyncManager asyn = new AsyncManager();

    public static AsyncManager asyn()
    {

        return asyn;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        ThreadUtils.shutdownAndAwaitTermination(executor,120);
    }
}



